<template>
  <ProjectInfo
    ref="projectInfoRef"
    :addRow="true"
    :addRowContent="'新增一行定性采样记录'"
    :preview="true"
    :projectId="`${route.query.projectId}`"
    :reportType="'GGIB'"
    :resetSampleNo="true"
    :sign="true"
    :signContent="'【定性采样】完成后进场签名，收样人进行交样，并且流程到【定性采样流转】'"
    :sync="true"
    :syncContent="'从现场调查中原辅材料中同步定性信息'"
    :needSignatureCheck="true"
    @delivery="delivery"
    @on-sync-header="getDefaultUnknownAnalysisSampling"
    @preview-file="toPreviewUnknownAnalysisRecord"
    @add-row="addRow"
    @reset-sample-no="resetSampleNo"
    @signature="handleSignature"
  />
  <ContentWrap>
    <div style="position: relative">
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="游离二氧化硅采样" name="silica">
          <QualitativeAnalysis
            ref="silicaAnalysisRef"
            :test-item="'游离二氧化硅含量测定'"
            @change="(data) => handleAnalysisChange(data, 'silica')"
          />
        </el-tab-pane>
        <el-tab-pane label="挥发性有机组采样" name="volatile">
          <QualitativeAnalysis
            ref="volatileAnalysisRef"
            :test-item="'挥发性有机组分定性分析'"
            @change="(data) => handleAnalysisChange(data, 'volatile')"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
  </ContentWrap>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { useRoute, useRouter } from 'vue-router'
import QualitativeAnalysis from './QualitativeAnalysis.vue'
import { ProjectApi } from '@/api/dk/project'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProjectInfo from '@/views/project/list/ProjectInfo.vue'

defineOptions({ name: 'UnknownAnalysis' })

const route = useRoute()
const router = useRouter()

// 从localStorage读取保存的tab状态，如果没有则默认为volatile
const activeTab = ref(localStorage.getItem('silica') || 'volatile')

/** 预览 */
const toPreviewUnknownAnalysisRecord = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 7
    }
  })
}

const volatileAnalysisRef = ref()
const silicaAnalysisRef = ref()
const projectInfoRef = ref()
const isInitializing = ref(false)

// 常量定义
const TEST_ITEMS = {
  volatile: '挥发性有机组分定性分析',
  silica: '游离二氧化硅含量测定'
} as const

const BASIS = {
  volatile: '《化学品中挥发性有机组分定性分析和峰面积百分比测定顶空气相色谱-质谱法》GDOHTQC 001—2020',
  silica: '《工作场所空气中粉尘测定第4部分：游离二氧化硅含量》GBZ/T 192.4-2007'
} as const

const DEFAULT_FORM = {
  taskNumber: '',
  sampleDate: new Date().toISOString().slice(0, 10),
  company: '',
  address: '',
  type: '定期检测'
}

const delivery = async () => {
  const projectId = route.query.projectId as string
  await ProjectApi.resetSampleNo(Number(projectId))
}

const resetSampleNo = async () => {
  const projectId = route.query.projectId as string
  await ProjectApi.resetSampleNo(Number(projectId))
  await volatileAnalysisRef.value.resetSampleNo()
  await silicaAnalysisRef.value.resetSampleNo()
}

const addRow = () => {
  const ref = activeTab.value === 'volatile' ? volatileAnalysisRef.value : silicaAnalysisRef.value
  if (ref) {
    ref.addRow()
  } else {
    ElMessage.warning('未能找到当前活动的分析组件来添加行。')
  }
}

// 监听 tab 切换
watch(activeTab, (newVal) => {
  // 保存当前选中的tab到localStorage
  localStorage.setItem('unknownAnalysisActiveTab', newVal)
})

// 处理表格行数据，补充默认值
const processTableRow = (row: any): any => ({
  ...row,
  model: row.model || '—',
  batch: row.batch || '—',
  manufacturer: row.manufacturer || '—',
  color: row.color || '',
  amount: row.amount || '',
  unit: row.unit || (row.physicalState && /液/.test(String(row.physicalState).trim()) ? 'ml' : 'g'),
  unitAuto: row.unitAuto !== undefined ? row.unitAuto : true,
  temperature: row.temperature || ''
})

// 处理从 API 返回的表格数据（tables -> table）
const processTablesData = (data: any): any[] => {
  if (!data.tables || !Array.isArray(data.tables)) return []
  return data.tables.map((row: any) => {
    // 如果 place 是数组，取第一个值作为字符串
    const processedRow = {
      ...row,
      place: Array.isArray(row.place) && row.place.length > 0 ? row.place[0] : row.place
    }
    return processTableRow(processedRow)
  })
}

// 处理现有表格数据（补充默认值）
const processExistingTable = (table: any[]): any[] => {
  if (!Array.isArray(table)) return []
  return table.map(row => ({
    ...row,
    model: row.model !== undefined && row.model !== null && row.model !== '' ? row.model : '—',
    batch: row.batch !== undefined && row.batch !== null && row.batch !== '' ? row.batch : '—',
    manufacturer: row.manufacturer !== undefined && row.manufacturer !== null && row.manufacturer !== '' ? row.manufacturer : '—',
    color: row.color || '',
    amount: row.amount || '',
    unit: row.unit || (row.physicalState && /液/.test(String(row.physicalState).trim()) ? 'ml' : 'g'),
    unitAuto: row.unitAuto !== undefined ? row.unitAuto : true,
    temperature: row.temperature || ''
  }))
}

// 设置表单数据
const setFormData = (type: 'volatile' | 'silica', data: any, isDefault = false) => {
  const ref = type === 'volatile' ? volatileAnalysisRef.value : silicaAnalysisRef.value
  if (!ref) return

  const processedData = { ...data }

  // 处理表格数据
  if (isDefault && processedData.tables) {
    processedData.table = processTablesData(processedData)
    delete processedData.tables
  } else if (processedData.table) {
    processedData.table = processExistingTable(processedData.table)
  }

  // 设置表单
  ref.form = isDefault
    ? {
        ...DEFAULT_FORM,
        basis: BASIS[type],
        item: TEST_ITEMS[type],
        ...processedData
      }
    : {
        ...processedData,
        item: TEST_ITEMS[type]
      }
}

// 保存数据
const saveData = async () => {
  const volatileData = volatileAnalysisRef.value?.form || {}
  const silicaData = silicaAnalysisRef.value?.form || {}

  if (volatileData.table?.length > 0 || silicaData.table?.length > 0) {
    await ProjectApi.updateUnknownAnalysisSampling({
      volatile: { data: volatileData },
      silica: { data: silicaData },
      currentChangeTab: 'volatile',
      projectId: route.query.projectId
    })
  }
}

// 处理 QualitativeAnalysis 组件的数据变化
const handleAnalysisChange = (data: any, type: 'volatile' | 'silica') => {
  if (isInitializing.value) return

  const volatileData = volatileAnalysisRef.value?.form || {}
  const silicaData = silicaAnalysisRef.value?.form || {}
  const projectId = route.query.projectId

  ProjectApi.updateUnknownAnalysisSampling({
    volatile: { data: type === 'volatile' ? data : volatileData },
    silica: { data: type === 'silica' ? data : silicaData },
    currentChangeTab: type,
    projectId: projectId
  })

  ElMessage.success('修改成功')
}

// 获取数据并返显
const getUnknownAnalysisSampling = async () => {
  const projectId = route.query.projectId
  if (!projectId) {
    console.warn('项目ID不能为空')
    return
  }

  isInitializing.value = true
  const data = await ProjectApi.getUnknownAnalysisSampling(Number(projectId))

  if (data.volatile?.data) setFormData('volatile', data.volatile.data)
  if (data.silica?.data) setFormData('silica', data.silica.data)

  await new Promise(resolve => setTimeout(resolve, 0))
  isInitializing.value = false
  ElMessage.success('同步成功')
}

const getDefaultUnknownAnalysisSampling = async () => {
  const projectId = route.query.projectId
  if (!projectId) {
    console.warn('项目ID不能为空')
    return
  }

  try {
    await ElMessageBox.confirm('同步后本地数据将被清空，确认是否继续同步？', '同步确认', {
      confirmButtonText: '确认同步',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch {
    return
  }

  isInitializing.value = true
  const data = await ProjectApi.getDefaultUnknownAnalysisSampling(Number(projectId))

  if (data.volatile?.data) setFormData('volatile', data.volatile.data, true)
  if (data.silica?.data) setFormData('silica', data.silica.data, true)

  await new Promise(resolve => setTimeout(resolve, 0))
  isInitializing.value = false
  await saveData()

  ElMessage.success('同步成功')
}

// 处理签名事件
const handleSignature = () => {
  // 先进行数据校验
  if (signatureCheck()) {
    // 校验通过，显示签名弹窗
    if (projectInfoRef.value) {
      projectInfoRef.value.showSignatureDialog()
    }
  }
  // 校验不通过时，不显示弹窗，错误信息已在 signatureCheck 中提示
}

// 校验签名前的数据完整性
const signatureCheck = (): boolean => {
  // 校验挥发性有机组分定性分析数据
  const volatileData = volatileAnalysisRef.value?.form
  if (volatileData) {
    const volatileError = validateFormData(volatileData, '挥发性有机组分定性分析')
    if (volatileError) {
      ElMessage.error(volatileError)
      activeTab.value = 'volatile'
      return false
    }
  }

  // 校验游离二氧化硅含量测定数据
  const silicaData = silicaAnalysisRef.value?.form
  if (silicaData) {
    const silicaError = validateFormData(silicaData, '游离二氧化硅含量测定')
    if (silicaError) {
      ElMessage.error(silicaError)
      activeTab.value = 'silica'
      return false
    }
  }

  return true
}

// 校验表单数据的通用方法
const validateFormData = (formData: any, formName: string): string | null => {
  // 校验头部信息
  if (!formData.sampleDate) {
    return `${formName}：请填写取样日期`
  }
  if (!formData.type) {
    return `${formName}：请填写检测类别`
  }

  // 校验表格数据
  if (!formData.table || !Array.isArray(formData.table) || formData.table.length === 0) {
    return `${formName}：至少需要添加一条记录`
  }

  // 校验每一行数据
  const requiredFields = [
    { key: 'sampleNo', label: '样品编号' },
    { key: 'materialName', label: '化学品原料/粉尘名称' },
    { key: 'physicalState', label: '样品性状' },
    { key: 'place', label: '取样场所、岗位、地点', isArray: true },
    { key: 'post', label: '代表/取样场所、岗位、地点', isArray: true },
    { key: 'amount', label: '取样量' },
    { key: 'unit', label: '单位' }
  ]

  for (let i = 0; i < formData.table.length; i++) {
    const row = formData.table[i]
    const rowIndex = i + 1

    for (const field of requiredFields) {
      const value = row[field.key]
      
      // 检查值是否为空
      let isEmpty = false
      
      if (value === undefined || value === null) {
        isEmpty = true
      } else if (field.isArray) {
        // 对于数组类型字段（place, post），检查是否为空数组
        if (Array.isArray(value) && value.length === 0) {
          isEmpty = true
        } else if (!Array.isArray(value) && (value === '' || String(value).trim() === '')) {
          // place 可能是字符串，也需要检查
          isEmpty = true
        }
      } else {
        // 对于字符串类型字段
        if (typeof value === 'string' && value.trim() === '') {
          isEmpty = true
        } else if (value === '') {
          isEmpty = true
        }
      }

      if (isEmpty) {
        return `${formName}：第${rowIndex}行的"${field.label}"不能为空`
      }
    }
  }

  return null
}

// 页面加载时获取数据
onMounted(() => {
  isInitializing.value = true
  getUnknownAnalysisSampling()
})

// 组件卸载时清理localStorage中的状态（可选，如果希望保持状态持久化可以注释掉）
onUnmounted(() => {
  localStorage.removeItem('unknownAnalysisActiveTab')
})
</script>

<style lang="scss" scoped>
:deep(.el-tabs__header) {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 15px; /* 确保按钮有空间显示 */
}

:deep(.el-tabs__nav-wrap) {
  flex-grow: 1;
  display: flex;
  align-items: center;
}

:deep(.el-tabs__item) {
  font-size: 14px;
  height: 40px;
  line-height: 40px;
}

.header-extra-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-shrink: 0;
  margin-left: 15px; /* 添加左侧间距 */
}
</style>
